<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 面板结构 -->
      <el-card v-loading="loading">
        <!-- 头部 -->
        <!-- 行列布局：栅格布局，将一行分为 24 份，每列占多少份由 el-col 身上的 span 属性决定。 -->
        <!-- type：flex 启用弹性布局。默认是使用的浮动布局 -->
        <!-- justify：flex 布局下的水平排列方式 -->
        <!-- align：flex 布局下的垂直排列方式 -->
        <TreeTools :item="header" :isheader="true" @show-dialog="showdialog" />
        <!-- 树形组件 -->
        <el-tree :data="list" :props="defaultProps">
          <!-- 使用插槽   解构data拿到数据-->
          <template #default="{data}">
            <TreeTools :item="data" @show-dialog="showdialog" @del="delFn" />
          </template>
        </el-tree>
      </el-card>

      <!-- 添加子部门弹窗 -->
      <el-dialog
        :title="title"
        :visible="dialogVisible"
        width="40%"
        @close="dialogClose"
        @open="dialogOpen"
      >
        <!-- 表单内容 -->
        <el-form ref="departRef" :model="departForm" :rules="departRules" label-width="120px">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="departForm.name" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="departForm.code" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <!-- <el-input v-model="departForm.manager" placeholder="请选择" /> -->
            <!-- 下拉菜单 -->
            <el-select v-model="departForm.manager">
              <el-option
                v-for="item in managerList"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="departForm.introduce" placeholder="1-300个字符" />
          </el-form-item>
        </el-form>
        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import TreeTools from './tree-tools.vue'
import { getDepartment, getManagerList, addDepartment, getDepartDetail, updateDepartment, delDepartment } from '@/api'
import transTree from '@/utils/transTree'
// import findSon from '@/utils/findSon'
export default {
  components: {
    TreeTools
  },
  data() {
  // 校验部门名称规则
    const validateName = (rules, value, callback) => {
      let booArr = []
      // 在编辑接口里的时候
      if (this.departForm.id) {
        // 如果输入的内容是当前节点的name  就通过
        if (value === this.nodeData.name) {
          callback()
          return
        } else {
          booArr = this.originList.filter(item => item.pid === this.nodeData.pid)
        }
      }
      booArr = this.originList.filter(item => item.pid === this.nodeData.id)
      const isSame = booArr.some(item => item.name === value)
      isSame ? callback(new Error('部门名称已经存在')) : callback()
    }
    // 校验部门编码  避免重复冲突
    const validateCode = (rules, value, callback) => {
      if (this.departForm.id && value === this.departForm.code) {
        callback()
        return
      }
      const isSame = this.originList.some(item => item.code === value)
      isSame ? callback(new Error('部门编码不能重复')) : callback()
    }
    return {
      managerList: [],
      loading: false,
      nodeData: {},
      // broArr: [],
      originList: [],
      // 表单校验规则
      departRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      departForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      dialogVisible: false,
      header: {
        name: '传智教育',
        manager: '负责人'
      },
      list: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  // 计算属性  判断有无id的情况下显示什么部门
  computed: {
    title() {
      return this.departForm.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.fetchgetDepartment()
  },
  methods: {
    // 删除部门
    delFn(val) {
      // 1. 询问用户
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delDepartment(val.id)
        this.$message.success('删除成功')
        this.fetchgetDepartment()
      })
    },
    // 刷新页面
    async fetchgetDepartment() {
      this.loading = true
      try {
        const res = await getDepartment()
        // this.list = findSon(res.data.depts)
        this.list = transTree(res.data.depts, '')
        // 原始数据
        this.originList = res.data.depts
        console.log(res)
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    // 提交新增子部门事件
    submit() {
      // 兜底校验
      this.$refs.departRef.validate(async valid => {
        if (!valid) return
        // 如果有id   就调用编辑接口
        if (this.departForm.id) {
          await updateDepartment(this.departForm)
          // 否则调用的是新增接口
        } else {
          await addDepartment({ ...this.departForm, pid: this.nodeData.id })
        }
        this.$message.success(this.title + '成功')
        this.dialogClose()
        this.fetchgetDepartment()
      })
    },
    dialogClose() {
      // 弹窗关闭
      this.dialogVisible = false
      // 弹窗关闭重置表单
      // this.$refs.departRef.resetFields()  只有在数据绑定el-form才能生效
      this.$refs.departRef.resetFields()
      // 重置数据
      this.departForm = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    // 获取部门详情
    async getDetail(id) {
      const res = await getDepartDetail(id)
      console.log(res)
      this.departForm = res.data
    },
    // 弹窗显示  并获取详情
    showdialog(nodeData, type) {
      if (type === 'edit') {
        this.getDetail(nodeData.id)
      }
      this.dialogVisible = true
      this.nodeData = nodeData
    },
    // 弹窗打开的回调
    async dialogOpen() {
      const { data } = await getManagerList()
      this.managerList = data
      // console.log(this.managerList)
    }
  }
}

</script>
<style lang='scss' scoped>
.app-container{
    padding: 20px;
}
.department-container{
  font-size: 10px;
  padding: 30px;
}
</style>
